#Package: samGSEA
#Title: Gene Set Enrichment Analysis (GSEA) based on Significance Analysis of Microarrays (SAM)
#Version: 1.0
#Date: 2013-12-04
#Author: Hoai Tuong Nguyen
#Maintainer: Hoai Tuong Nguyen <hoai-tuong.nguyen@inserm.fr>
#Description: The package provides methods for identifying the differently significant genes by using Gene Set Enrichment Analysis (GSEA) based on Significance Analysis of Microarrays (SAM).
#License: GPL
#LazyLoad: yes



#'@name samt
#'@aliases samt
#'@export samt
#'@docType methods
#'@title Adapted version of samr 
#'@description An adapted version of samr for gene differtiation analysis
#'@param df a microarray dataframe 
#'@param label vector of label
#'@param nperms number of permutations
#'@param logged2 logical. Expression level has been transformed by logorith base 2
#'@author Hoai Tuong Nguyen
#'@examples
#'0
samt<-function(df,label,nperms=100,logged2=T,type="Two class unpaired",seq=F){
  if(logged2)
    df<-log2(df)
  
  if (!seq){
    samfit<-SAM(x=df,y=label, geneid=as.character(1:nrow(df)),genenames=rownames(df), logged2=logged2, resp.type=type, nperms=nperms,testStatistic="wilcoxon",fdr.output = 0.20)
  }else {
    samfit<-SAMseq(x=df,y=label, geneid=as.character(1:nrow(df)),genenames=rownames(df), logged2=logged2, resp.type=type, nperms=nperms,testStatistic="wilcoxon",fdr.output = 0.20)
  }
  
  samr.obj<-samfit$samr.obj
  siggenes.table<-samfit$siggenes.table
  
  
  pv=samr.pvalues.from.perms(samr.obj$tt, samr.obj$ttstar)

  if(is.null(siggenes.table$ngenes.up)&is.null(siggenes.table$ngenes.lo))
    res.list=NULL
  else{
    res<-rbind(siggenes.table$genes.up,siggenes.table$genes.lo)
    
    res.list<-list(probeID=res[,1],
                   UpLow=c(rep("UP",siggenes.table$ngenes.up),rep("LOW",siggenes.table$ngenes.lo)),
                   Stat=res[,3],
                   RawpValue=pv[res[,1]],
                   FoldChange=res[,6],
                   FDR=res[,7],
                   nsiggenes=siggenes.table$ngenes.up+siggenes.table$ngenes.lo)

  }
   
  return(res.list)
}

#'@name samt.opt
#'@aliases samt.opt
#'@export samt.opt
#'@docType methods
#'@title Optimized version of samr 
#'@description An optimized version of samr for gene differtiation analysis
#'@param df a microarray dataframe 
#'@param label vector of label
#'@param nmax.perms number of maximum permutations
#'@param logged2 logical. Expression level has been transformed by logorith base 2
#'@author Hoai Tuong Nguyen
#'@examples
#'0
samt.opt<-function(df,label,nmax.perms=100, logged2=T,type="Two class unpaired",seq=F){
  if(logged2)
    df<-log2(df)
  
  bins<-seq(10,nmax.perms,10)
  
  out.log<-do.call(rbind,sapply(bins,function(t){
    samres<-samt(df, label,t,logged2,type,seq=seq)
    if(!is.null(samres$nsiggenes))
      list(c(nperms=t,nsiggenes=samres$nsiggenes,samres=samres))
  }
  ))
  #nperms.opt<-as.numeric(out.log[which(unlist(out.log[,2])==max(unlist(out.log[,2]))),1])
  
  #samres.opt<-out.log[which(unlist(out.log[,2])==max(unlist(out.log[,2]))),3:ncol(out.log)]
  #print(paste("Optimal number of permuations:",nperms.opt))
  #print(out.log)
  #plot(out.log[,1:2])
  
  return(out.log)
}




#'@name samr.opt.cluster
#'@aliases samr.opt.cluster
#'@export samr.opt.cluster
#'@docType methods
#'@title Optimized version of samr with clusters
#'@description An optimized version of samr with cluster for gene differtiation analysis
#'@param df a microarray dataframe 
#'@param label vector of label
#'@param nmax.perms number of maximum permutations
#'@param logged2 logical. Expression level has been transformed by logorith base 2
#'@author Hoai Tuong Nguyen
#'@examples
#'0
samr.opt.cluster<-function(df,class,label=NULL,file,index=NULL,cluster,type="Two class unpaired",logged2=T,nmax.perms=200,seq=F){
  print(cluster)
  
  print(is.null(nrow(df)))
  if (!is.null(nrow(df)))
    if ( nrow(df)>=10){
      
      if (exists("class")&is.null(label)){
        print("OK")        
label<-as.vector(class[colnames(df),4])
        label<-label+1
      }
      print(label)
      sig<-samt.opt(df, 
                    label,
                    nmax.perms=nmax.perms,
                    logged2=logged2,
                    type=type,
                    seq=seq)

      print(sig)
        if (!is.null(sig)){
          if(ncol(sig)==1)
          sig.tab<-do.call(rbind,sapply(1:nrow(sig),function(x) list(cbind(unlist(as.list(sig[[1]])[3]),
                                                                           unlist(as.list(sig[[1]])[4]),
                                                                           unlist(as.list(sig[[1]])[5]),
                                                                           unlist(as.list(sig[[1]])[6]),
                                                                           unlist(as.list(sig[[1]])[7]),
                                                                           unlist(as.list(sig[[1]])[8])))))
          else 
            sig.tab<-do.call(rbind,sapply(1:nrow(sig),function(x) list(cbind(unlist(sig[x,3]),
                                                                             unlist(sig[x,4]),
                                                                             unlist(sig[x,5]),
                                                                             unlist(sig[x,6]),
                                                                             unlist(sig[x,7]),
                                                                             unlist(sig[x,8])))))
          
      siggenes.final<-unique(sig.tab[,1])
      
      print(sig.tab)
      print(siggenes.final)

      sig.tab.final<-do.call(rbind,sapply(1:length(siggenes.final),function(x) {
        idv.tab<-sig.tab[sig.tab[,1]==siggenes.final[x],]
        if(!is.null(dim(idv.tab)))
          list(idv.tab[order(idv.tab[,4])[1],])
        else list(idv.tab)
        }))
      
 

      if (!is.null(siggenes.final)){
        print(sig.tab.final)
        if(nrow(sig.tab.final)==1)
          res.sig<-data.frame(sig.tab.final[1],
                              rep(index,nrow(sig.tab.final)),
                              sig.tab.final[2],
                              sig.tab.final[3],
                              sig.tab.final[4],
                              sig.tab.final[5],
                              sig.tab.final[6],
                              rep(gsub("-",":",cluster),nrow(sig.tab.final)))
        else
          res.sig<-data.frame(sig.tab.final[,1],
                              rep(index,nrow(sig.tab.final)),
                              sig.tab.final[,2],
                              sig.tab.final[,3],
                              sig.tab.final[,4],
                              sig.tab.final[,5],
                              sig.tab.final[,6],
                              rep(gsub("-",":",cluster),nrow(sig.tab.final)))
        colnames(res.sig)<-c("PROBEID", "Index", "UpLow", "Stat",    "RawpValue",   "FoldChange", "FDR","GOID")
        outfile<-sprintf("%s_%s.csv",file,index)
        write.table(res.sig,file=outfile,col.names=F,row.names=F,quote=F,sep="\t",append=TRUE)    
        print(paste("Results written to: ",getwd(),"/",outfile,sep=""))
      }
      }
      return(sig)
    }
  
}

